package com.cola.service.auth;

import com.cola.entity.WeChatInfo;
import com.cola.utils.HttpUtils;
import com.cola.utils.PropertyUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;

/**
 * 处理微信相关接口的业务逻辑类
 * @author Max
 * @since 2017/9/12
 */
public class WeChatService {
	private static final Logger logger = Logger.getLogger(WeChatService.class);

	/**
	 * 获取授权用户微信信息
	 * @param code
	 * @return Map<String,String> 用户微信信息
	 * @author Max
	 * @since 2017/9/12
	 */
	public Map<String,String> getAccessToken(String code){
		Map<String,String> tokenMap=new HashMap<String, String>();
		String accessToken="";
		String openid="";
		String url= PropertyUtils.getProperty("getTokenUrl");
		url= HttpUtils.getParms(url,"appid",PropertyUtils.getProperty("appid"));
		url=HttpUtils.getParms(url,"secret",PropertyUtils.getProperty("appsecret"));
		url=HttpUtils.getParms(url,"code",code);
		url=HttpUtils.getParms(url,"grant_type","authorization_code");
		String result=HttpUtils.sendGet(url);
		try{
			if(StringUtils.isNotEmpty(result)){
				JSONObject jsonResult=new JSONObject(result);
				if(jsonResult.has("access_token")&&jsonResult.has("openid")){
					accessToken=jsonResult.getString("access_token");
					openid=jsonResult.getString("openid");
					tokenMap.put("access_token", accessToken);
					tokenMap.put("openid", openid);
				}
			}
		}catch(Exception e){
			logger.error("获取授权用户微信信息异常",e);
		}
		return tokenMap;
	}

	/**
	 * 根据access_token和openid获取用户详情
	 * @param accessToken
	 * @param openid
	 * @return Map<String, Object>
	 * @author Max
	 * @since 2017/9/12
	 */
	public WeChatInfo getWeChatUserInfo(String accessToken, String openid) {
		String url=PropertyUtils.getProperty("getUserInfoUrl");
		url=HttpUtils.getParms(url,"access_token",accessToken);
		url=HttpUtils.getParms(url,"openid",openid);
		url=HttpUtils.getParms(url,"lang","zh_CN");
		String result=HttpUtils.sendGet(url);
		try{
			if(StringUtils.isNotEmpty(result)){
				return com.alibaba.fastjson.JSONObject.parseObject(result,WeChatInfo.class);
			}
		}catch(Exception e){
			logger.error("",e);
		}
		return null;
	}
}
